package com.xingkeduo.configuration;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class WechatFilter implements HandlerInterceptor {
	Logger log = LoggerFactory.getLogger(WechatFilter.class);

    public final static ThreadLocal<Long> operateIdThreadLocal = new ThreadLocal<>();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String requestURI = request.getRequestURI();
        String queryString = request.getQueryString();
        String method = request.getMethod();

        log.info("===============================");
        log.info("url 开始验证:{}", requestURI);
        if (StringUtils.isNotBlank(queryString)) {
            log.info("queryString:{}", queryString);
        }
        log.info("===============================");

        try {
            operateIdThreadLocal.set(Long.parseLong(request.getHeader("operator")));
        } catch (NumberFormatException e) {
            operateIdThreadLocal.set(0L);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        operateIdThreadLocal.remove();
    }

}
